package sen.myReport;

import java.io.File;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sen.queryUtils.MyUtils;

import sen.queryUtils.Cond;
import sen.queryUtils.ConditionalFactory;
import sen.queryUtils.Results;

/**
 * 基于struts1.x
 * @author sen
 *
 */
public class MyReportAction extends BasicAction {
	
	private static final Logger LOG = LoggerFactory.getLogger(MyReportAction.class);
	
	private MyReportService myReportService;
	private float maxSizeFile;
	private String fileType;
	
	public ActionForward query(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<Cond> cond = ConditionalFactory.getInstance().createConditional(getParam(request, Constant.ACTION_METHOD_NAME+","+Constant.REQUEST_REPORT_ID));
		String reqReportId = request.getParameter(Constant.REQUEST_REPORT_ID);
		Results r = myReportService.query(reqReportId, cond);
		request.setAttribute(Constant.RESULTS_NAME, r);
		
		String responsePage = myReportService.getResponsePage(reqReportId);
		return new ActionForward(responsePage);
	}
	
	public ActionForward downloadReport(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		List<Cond> cond = ConditionalFactory.getInstance().createConditional(getParam(request, Constant.ACTION_METHOD_NAME+","+Constant.REQUEST_REPORT_ID));
		String reqReportId = request.getParameter(Constant.REQUEST_REPORT_ID);
		
		MyReportData rd = myReportService.getReportData(reqReportId, cond);
		
		OutputStream os = response.getOutputStream();
	    response.reset();
	    response.setContentType("application/vnd.ms-excel;charset=utf-8");
	    String filename = new String((rd.getMyReportName()).getBytes("GBK"),"ISO8859_1");
	    response.setHeader("Content-Disposition", "attachment;filename="+ filename);
	    os.write(rd.getDatas());
	    rd.setDatas(null);
	    response.getOutputStream().flush();
	    response.getOutputStream().close();
		return null;
	}
	
	public ActionForward importReport(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<Object[]> info = new ArrayList<Object[]>();//存错误信息
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			
			int businessType = Integer.parseInt(request.getParameter("type"));
			
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			Iterator items = null;
			items = upload.parseRequest(request).iterator();
			while (items.hasNext()) {
				FileItem item = (FileItem) items.next();
				if (!item.isFormField()) {
					//取出上传文件的文件名称
					String name = item.getName();
					if(MyUtils.isNull(name)){
						info.add(new Object[]{0,"没有选择文件！"});
						continue;
					}
					String type = name.substring(name.lastIndexOf('.'),name.length());
					//检查文件类型
					if(!type.matches(fileType)){
						info.add(new Object[]{0,"【"+name+"】只能上传excel文件！"});
						continue;
					}
					//检查文件大小
					long size = item.getSize();
					if(size > maxSizeFile){
						info.add(new Object[]{0+"","【"+name+"】文件大小有限，不能超过"+(maxSizeFile/1024/1024)+"M。"});
						continue;
					}
					String dateStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
					String fileName = "temp_"+dateStr+type;
					String path = request.getRealPath("upload")+File.separatorChar+fileName;
					//上传文件
					File uploadedFile = new File(path);
					try {
						item.write(uploadedFile);
					} catch (Exception e1) {
						LOG.error(e1.getLocalizedMessage());
						info.add(new Object[]{0,"文件上传出现问题！"});
					}
					try {
						//开始导进数据库
//						financeService.processImport(path,
//								businessType,
//								Integer.parseInt(item.getFieldName())
//								);
						
						info.add(new Object[]{1,"【"+name+"】"});
					} catch (NumberFormatException e) {
						LOG.error(e.getLocalizedMessage());
						info.add(new Object[]{0,"【"+name+"】文件上传成功，但导入系统时出现问题。（注：字符串转整形问题）"});
					} catch (Exception e) {
						e.printStackTrace();
						LOG.error(e.getLocalizedMessage());
						info.add(new Object[]{0,"【"+name+"】文件上传成功，但导入系统时出现问题。"+e.getLocalizedMessage()});
					}
					uploadedFile.delete();
				}
			}
		}
		request.setAttribute("info", info);
		request.setAttribute("resId", request.getParameter("resId"));
		return new ActionForward("/finance/QNE_initData_res.jsp");
	}
	
	public void setMyReportService(MyReportService myReportService) {
		this.myReportService = myReportService;
	}

	public void setMaxSizeFile(float maxSizeFile) {
		this.maxSizeFile = maxSizeFile;
	}

	public void setFileType(String fileType) {
		this.fileType = fileType;
	}
}